import { SessionService } from './session-service';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import { HttpResponse } from "@angular/common/http";
import { HttpErrorResponse } from "@angular/common/http";
import { Router } from "@angular/router";
import { MdlSnackbarService } from "@angular-mdl/core/components";

export class CustomError {
    errCode: string;
    msg: string;

    constructor(errResp: any) {
        this.errCode = errResp.errCode;
        this.msg = errResp.msg;
    }
}

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(
        private _sessionService: SessionService,
        private _router: Router,
        private _mdlSnackbarService: MdlSnackbarService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('........inteceptor .......');
        let token = this._sessionService.getToken();

        let authReq = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) });

        return next.handle(authReq)
            .map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    console.log('*An intercepted httpResponse*', event);
                    let body = event.body;
                    if (body.errCode) {
                        throw new CustomError(body);
                    }

                    return event;
                }
            })
            .catch((error: any) => {
                if (error instanceof HttpErrorResponse) {
                    if (error.status === 403) {
                        // return this.tokenService
                        //     .obtainAccessToken()
                        //     .flatMap((token) => {
                        //         const authReqRepeat = this.authenticateRequest(req);
                        //         console.log('*Repeating httpRequest*', authReqRepeat);
                        //         return next.handle(authReqRepeat);
                        //     });
                    }
                    if (error.status === 401) {
                        console.error('not auth');
                        this._router.navigate(['/login']);
                    }
                } else if (error instanceof CustomError) {
                    console.log(error.msg);
                    this._mdlSnackbarService.showToast(error.msg, 2000);
                    return Observable.throw(error);
                } else {
                    return Observable.throw(error);
                }
            });
    }
}